# -*- coding: utf-8 -*-

import os
import logging
import logging.handlers
from misc.thread_local import get_msg_id


class MsgFormatter(logging.Formatter):
    def __init__(self, fmt=None, datefmt=None):
        logging.Formatter.__init__(self, fmt, datefmt)

    def format(self, record):
        msg_id = get_msg_id()
        if msg_id == "":
            record.msg_id = ""
        else:
            record.msg_id = "(%s)" % msg_id

        return logging.Formatter.format(self, record)


def create_logger(logger_name, log_path=None):
    if log_path is None:
        log_path = '/var/log/kellan'

    global g_logger_name
    global g_log_path
    # if the logger has been created, do not create another one
    if logger_name == g_logger_name and log_path == g_log_path:
        return

    # prepare the log directory
    os.system('mkdir -p {0}'.format(log_path))

    # create formatter
    fmt = '%(asctime)s.%(msecs)d %(levelname)s %(process)d %(thread)d %(message)s (%(filename)s:%(lineno)d)%(msg_id)s'
    datefmt = '%Y-%m-%d %H:%M:%S'
    formatter = MsgFormatter(fmt, datefmt)

    # create file handler, which to log all logs
    log_file = log_path + '/' + logger_name + '.log'
    # create the rotating file handler, 100MB
    fh = logging.handlers.RotatingFileHandler(log_file, mode='a', maxBytes=100000000, backupCount=3)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)

    # create the wf file handler, which to log the wf logs
    log_wf_file = log_path + '/' + logger_name + '.log.wf'
    # create the wf rotating file handler, 100MB
    fh_wf = logging.handlers.RotatingFileHandler(log_wf_file, mode='a', maxBytes=100000000, backupCount=3)
    fh_wf.setLevel(logging.ERROR)
    fh_wf.setFormatter(formatter)

    # create logger
    _logger = logging.getLogger(logger_name)
    _logger.setLevel(logging.DEBUG)

    # add file handlers to logger
    _logger.addHandler(fh)
    _logger.addHandler(fh_wf)

    # make global variable has new value
    global logger
    logger = _logger
    g_logger_name = logger_name
    g_log_path = log_path

g_logger_name = None
g_log_path = None
logger = None
if logger is None:
    # if not create new logger, the installer logger is default
    create_logger('kellan', '/var/log/kellan')
